import {
  ref
} from 'vue'
import {
  defineStore
} from 'pinia'

import {
  Api
} from '@/js/api.js'

const USER_KEY = 'uniapp_user'

const saveUser = (user) => {
  uni.setStorageSync(USER_KEY, user)
}

const loadUser = () => {
  let user = uni.getStorageSync(USER_KEY)
  if (user) {
    return user
  }
  return {
    isLogin: false,
    user: {},
    userInfo: {},
    userStatistics: {}
  }
}

export const useUserStore = defineStore('user', () => {
  const suser = loadUser()

  const user = ref(suser.user)
  const userInfo = ref(suser.userInfo)
  const userStatistics = ref(suser.userStatistics)
  const isLogin = ref(suser.isLogin)
  const userLogo = ref(
    suser.user.id ? Api.userlogo(suser.user.id) : ''
  )
  const updateUserInfo = (cb) => {

    Api.get('/auth/info', {}, (data) => {
      isLogin.value = data.success
      if (data.success) {
        user.value = data.data.user
        userInfo.value = data.data.info
        userStatistics.value = data.data.statistics
        userLogo.value = Api.userlogo(user.value.id)
      } else {
        user.value = {}
        userInfo.value = {}
        userStatistics.value = {}
        userLogo.value = ''
      }
      saveUser({
        isLogin: isLogin.value,
        user: user.value,
        userInfo: userInfo.value,
        userStatistics: userStatistics.value
      })
      cb(data.success)
    })
  }


  return {
    user,
    userInfo,
    userStatistics,
    isLogin,
    userLogo,
    updateUserInfo
  }

})